<template>
  <div class="app-container home">
    <el-row style="padding: 0px 10px 20px;">
      <el-button type="primary" icon="el-icon-search" circle @click="listVisualUser"></el-button>
      <el-button type="primary" icon="el-icon-plus" circle @click="handleAdd"></el-button>
    </el-row>

    <el-row :gutter="20" class="dataList">
      <div v-if="!grantList || grantList.length<=0" style="padding: 20px; text-align: center; color: #bababa;">无数据</div>
      <el-col :xs="24" :sm="24" :md="12" :lg="8" v-for="(grant) in grantList" style="margin-bottom: 5px; cursor: pointer;">
        <el-card class="update-log">
          <div slot="header" class="clearfix">
            <span>{{grant.nickName}}</span>
            <i style="float:right; color: #bcbec2;" class="el-icon-delete" @click="removeVisualUser(grant)"> </i>
          </div>
          <div class="body">
            <p>{{grant.remark}}</p>
            <div style="color: #606266">
              <span v-if="grant.grants">授予：</span>
              <span v-for="g in grant.grants">{{g.toUser + '，'}}</span>
            </div>
            <div slot="footer" class="dialog-footer" style="text-align: right">
              <i class="el-icon-user" @click="handleGrant(grant)" style="color: #606266; margin-left: 10px;"> 授予</i>
              <i class="el-icon-info" @click="handleEdit(grant)" style="color: #606266; margin-left: 10px;"> 详情</i>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :title="dialog.title" :visible.sync="dialog.open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="账号名称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入虚拟账号名称" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!menuCheckStrictly"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="grantDialog.title" :visible.sync="grantDialog.open" width="500px" append-to-body>
      <el-form ref="formGrant" :model="grantDialog.form" :rules="rulesGrant" label-width="80px">
        <el-form-item label="授予用户" prop="toUser">
          <el-select
            v-model="grantDialog.form.toUser"
            filterable remote reserve-keyword clearable
            placeholder="请输入关键字" :remote-method="loadUserList" :loading="grantDialog.loading">
            <el-option v-for="item in grantDialog.selectUserList" :key="item.userName" :label="item.nickName" :value="item.userName">
              <span style="float: left">{{ item.nickName+'('+item.userName+')'}}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dept.deptName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" v-model="grantDialog.form.endTime" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-col>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="grantDialog.open=false">取 消</el-button>
        <el-button type="primary" @click="submitGrant">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import {roleMenuTreeselectForVisualUser} from "@/api/system/menu";
    import {
        createVisualUser,
        getVisualUser,
        grantVisualUser,
        listVisualUser,
        removeVisualUser,
        updateVisualUser
    } from "@/api/system/visualUser";
    import {listUser} from "@/api/system/user";

    export default {
  name: "Grant",
  components: {},
  data() {
    return {
        grantList: [],
        dialog: {
            open: false,
            title: "创建虚拟账号"
        },
        grantDialog: {
            open: false,
            title: "授予",
            selectUserList: [],
            loading: false,
            form: {
            }
        },
        form: {},
        defaultProps: {
            children: "children",
            label: "label"
        },
        menuOptions: [],
        menuExpand: false,
        menuNodeAll: false,
        menuCheckStrictly: true,
        rules: {
            nickName: [
                { required: true, message: "虚拟账号名称", trigger: "blur" }
            ]
        },
        rulesGrant: {
            toUser: [
                { required: true, message: "必须选择授予用户", trigger: "blur" }
            ],
            endTime: [
                { required: true, message: "必须选择截止日期", trigger: "blur" }
            ],
        }
    };
  },
  watch: {
  },
  mounted() {
      this.listVisualUser();
  },
  created() {
  },
  methods: {
      handleAdd() {
          this.reset();
          this.loadMenu(0);
          this.dialog.open = true;
          this.dialog.title = "创建虚拟账号";
      },
      handleEdit(row) {
          this.reset();
          getVisualUser(row.userId).then(response => {
              this.form = response.data;
              this.dialog.open = true;
              const loadMenuFun = this.loadMenu(row.userId);
              this.$nextTick(() => {
                  loadMenuFun.then(res => {
                      let checkedKeys = res.data.checkedKeys
                      checkedKeys.forEach((v) => {
                          this.$nextTick(()=>{
                              this.$refs.menu.setChecked(v, true ,false);
                          })
                      })
                  });
              });
              this.dialog.title = "修改虚拟账号";
          });
      },
      handleGrant(row) {
          this.reset();
          this.grantDialog.open = true;
          this.grantDialog.form = {
              visualUserId: row.userId,
              fromUser: row.userName,
              toUser: null,
              startTime: null,
              endTime: null,
              isActive: true
          }
      },
      // 表单重置
      reset() {
          if (this.$refs.menu != undefined) {
              this.$refs.menu.setCheckedKeys([]);
          }
          this.menuExpand = false,
          this.menuNodeAll = false,
          this.form = {};
          this.resetForm("form");
          this.resetForm("formGrant");
          this.grantDialog = {
              open: false,
              title: "授予",
              selectUserList: [],
              loading: false,
              form: {
              }
          };
      },
      /** 根据用户id查询所有的 */
      loadMenu(vuserId) {
          return roleMenuTreeselectForVisualUser(vuserId).then(response => {
              this.menuOptions = response.data.menus;
              return response;
          });
      },
      /** 提交按钮 */
      submitForm: function() {
          this.$refs["form"].validate(valid => {
              if (valid) {
                  this.form.menuIds = this.getMenuAllCheckedKeys();
                  if (this.form.userId) {
                      updateVisualUser(this.form.userId, this.form).then(res => {
                          this.msgSuccess("更新成功");
                          this.dialog.open = false;
                          this.listVisualUser();
                      })
                  } else {
                      createVisualUser(this.form).then(res => {
                          this.msgSuccess("保存成功");
                          this.dialog.open = false;
                          this.listVisualUser();
                      });
                  }
              }
          });
      },
      submitGrant: function() {
          this.$refs["formGrant"].validate(valid => {
              if (valid) {
                  this.$confirm('确认要授权给该用户'+this.grantDialog.form.toUser, "提示", {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning"
                  }).then(() => {
                      return grantVisualUser(this.grantDialog.form.visualUserId, this.grantDialog.form);
                  }).then((res) => {
                      this.msgSuccess("删除成功");
                      this.grantDialog.open = false;
                      this.listVisualUser();
                  });
              }
          });
      },
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
          // 目前被选中的菜单节点
          let checkedKeys = this.$refs.menu.getCheckedKeys();
          // 半选中的菜单节点
          let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
          checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
          return checkedKeys;
      },
      // 取消按钮
      cancel() {
          this.dialog.open = false;
          this.grantDialog.open = false;
          this.reset();
      },
      // 树权限（展开/折叠）
      handleCheckedTreeExpand(value, type) {
          if (type == 'menu') {
              let treeList = this.menuOptions;
              for (let i = 0; i < treeList.length; i++) {
                  this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
              }
          } else if (type == 'dept') {
              let treeList = this.deptOptions;
              for (let i = 0; i < treeList.length; i++) {
                  this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
              }
          }
      },
      // 树权限（全选/全不选）
      handleCheckedTreeNodeAll(value, type) {
          if (type == 'menu') {
              this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
          } else if (type == 'dept') {
              this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
          }
      },
      // 树权限（父子联动）
      handleCheckedTreeConnect(value, type) {
          if (type == 'menu') {
              this.form.menuCheckStrictly = value ? true: false;
          } else if (type == 'dept') {
              this.form.deptCheckStrictly = value ? true: false;
          }
      },
      listVisualUser() {
          const loading = this.$loading({
              lock: true,
              text: '正在查询数据',
              spinner: 'el-icon-loading',
              target: '.dataList'
          });
          listVisualUser().then(
              response => {
                  this.grantList = response.data;
                  loading.close();
              }
          );
      },
      removeVisualUser(account) {
          this.$confirm('确认要删除虚拟用户'+account.nickName, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          }).then(() => {
              return removeVisualUser(account.userId)
          }).then((res) => {
              this.msgSuccess("删除成功");
              this.listVisualUser();
          });
      },
      //关键字检索用户
      loadUserList(queryString) {
          this.grantDialog.selectUserList = [];
          if(!queryString) {
              return;
          }
          listUser({pageNum: 1, pageSize: 20, userName: queryString}).then(
              response => {
                  this.grantDialog.selectUserList = response.rows;
              }
          );
      },
  }
};
</script>

<style scoped lang="scss">
.home {
  el-col {
    cursor: pointer;
    margin-bottom: 5px;
  }
}
</style>
